<?php

/**
 * Devel Generate batch handling functions using the BatchAPI
 */

/**
 * Functions called from FAPI:
 */

function wordgame_word_import_words_batch($form_state) {
  static $words;

  if (!isset($words)) {
    $words = wordgame_word_load_words();
  }

  $operations = array();
  $imported_words = variable_get('wordgame_word_imported_words', array());

  // Setup the batch operations and save the variables.
  $operations[] = array('wordgame_word_import_words_batch_prepare', array($form_state['values'], $imported_words));

  $limit = $form_state['values']['wordgame_word_import_limit'];

  $items = array();
  foreach($words as $key => $word) {
    if (!isset($imported_words[$key])) {
      if (count($items) < $limit) {
        if (!preg_match("/\\s|\\-/", $key)) {
          $items[$key] = $word;
        }
      }
    }
  }

  // add the operations to create the nodes
  foreach ($items as $word => $item) {
    $operations[] = array('wordgame_word_import_words_batch_add_word', array($word, $item));
  }

  // start the batch
  $batch = array(
    'title' => t('Generating Content'),
    'operations' => $operations,
    'init_message'     => t('Starting...'),
    'progress_message' => t('Processing...'),
    'finished' => 'wordgame_word_import_words_batch_finished',
    'file' => drupal_get_path('module', 'wordgame_word') . '/wordgame_word_import_batch.inc',
  );
  batch_set($batch);
}


function wordgame_word_import_words_batch_prepare($vars, $imported_words, &$context) {
  $context['results'] = $vars;
  $context['results']['num_wid'] = 0;
  $context['results']['words'] = $imported_words;
}

function wordgame_word_import_words_batch_add_word($word, $data, &$context) {
  $context['results']['num_wid'] ++;
  $context['results']['words'][$word] = $data;
  // Repair word
  $record = new StdClass();
  $record->word = $word;
  $record->length = strlen(trim($word));
  $record->meaning = '';//wordgame_word_get_meaning($data['offset'], $data['length']);
  $record->dict = 'en_vi';
  $record->offset = $data['offset'];
  $record->amount = $data['length'];

  wordgame_word_save($record);
  variable_set('wordgame_word_imported_words', $context['results']['words']);
}

function wordgame_word_import_words_batch_finished($success, $results, $operations) {

  if ($success) {
    $message = t('Finished @num_wid words created successfully.', array('@num_wid' => $results['num_wid']));
  }
  else {
    $message = t('Finished with an error.');
  }
  drupal_set_message($message);
}

